package com.hsxxherp.ation.common.utils;

import com.google.common.collect.Lists;
import com.hsxxherp.ation.common.annotation.Required;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.*;


public class BeanUtils {

    private static final Logger log = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * 检验bean必输属性
     */
    public static void checkRequiredFields(Object bean) {
        List<String> requiredFields = Lists.newArrayList();

        List<Field> fields = new ArrayList<>(Arrays.asList(bean.getClass().getDeclaredFields()));
        fields.addAll(Arrays.asList(bean.getClass().getSuperclass().getDeclaredFields()));
        for (Field field : fields) {
            try {
                boolean isAccessible = field.isAccessible();
                field.setAccessible(true);
                if (field.isAnnotationPresent(Required.class)) {
                    // 两种情况，一种是值为null，
                    // 另外一种情况是类型为字符串，但是字符串内容为空的，都认为是没有提供值
                    boolean isRequiredMissing = field.get(bean) == null
                            || (field.get(bean) instanceof String
                            && StringUtils.isBlank(field.get(bean).toString())
                    );
                    if (isRequiredMissing) {
                        requiredFields.add(field.getName());
                    }
                }
                field.setAccessible(isAccessible);
            } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * map转对象
     *
     * @param map
     * @param object
     * @return  ojbect
     */
    public static Object mapToObject(Map<String,Object> map,Object object) {
        // 获取字段
        List<Field> fields = new ArrayList<>(Arrays.asList(object.getClass().getDeclaredFields()));
        fields.addAll(Arrays.asList(object.getClass().getSuperclass().getDeclaredFields()));
        for (Field field : fields) {
            try {
                boolean isAccessible = field.isAccessible();
                field.setAccessible(true);
                String fieldName = StringUtil.camelCaseToUnderscore(field.getName());
                if (!Objects.isNull(map.get(fieldName))) {
                    field.set(object,map.get(fieldName));
                }
                log.info("获取到的字段名为：{}",StringUtil.camelCaseToUnderscore(field.getName()));
                field.setAccessible(isAccessible);
            } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
                log.error(e.getMessage(), e);
            }
        }
        log.info("接受到的类{}",fields.toString());
        return object;
    }
 }
